package org.xyz.util;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.widget.CheckBox;
import android.widget.EditText;

public final class StringHelper {

	public static final String merger(String s1, String s2, String defaultS2) {
		StringBuffer mSm = new StringBuffer();
		mSm.append(s1);
		mSm.append(": ");
		if (StringHelper.isText(s2)) {
			mSm.append(s2);
		} else {
			mSm.append(defaultS2);
		}
		return mSm.toString();
	}

	public final static String STR_SEPARATOR = ",";

	/**
	 * 筛除非法字符
	 * 
	 * @param text
	 * @return
	 */
	final public static boolean isText(String text) {
		if (text == null || text.length() == 0 || text.equals("")
				|| text.equals("null") || text.equals("NULL")) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 判断用户是否输入
	 * 
	 * @param context
	 * @param text
	 * @return
	 */
	final public static String checkText(String text) {
		if (isText(text)) {
			return text;
		}
		return "";
	}

	/**
	 * 去除最后的连接符号
	 * 
	 * @param source
	 * @param separator
	 * @return
	 */
	final public static String removeLastSeparator(String source,
			String separator) {
		if (isText(source)) {
			if (source.endsWith(separator)) {
				source = source.substring(0, source.length() - 1);
			}
		}
		return source;
	}

	/**
	 * 去除特殊字符或将所有中文标号替换为英文标号
	 * 
	 * @param str
	 * @return
	 */
	final public static String stringFilter(String str) {
		str = str.replaceAll("【", "[").replaceAll("】", "]")
				.replaceAll("！", "!").replaceAll("：", ":").replaceAll("（", "(")
				.replaceAll("）", ")").replaceAll("“", "\"")
				.replaceAll("”", "\"");// 替换中文标号
		String regEx = "[『』]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("").trim();
	}

	// 半角转化为全角的方法
	final public static String ToSBC(String input) {
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 32) {
				c[i] = (char) 12288;
				continue;
			}
			if (c[i] < 127 && c[i] > 32)
				c[i] = (char) (c[i] + 65248);
		}
		return new String(c);
	}

	// 全角转化为半角的方法
	final public static String ToDBC(String input) {
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (isChinese(c[i])) {
				if (c[i] == 12288) {
					c[i] = (char) 32;
					continue;
				}
				if (c[i] > 65280 && c[i] < 65375)
					c[i] = (char) (c[i] - 65248);
			}
		}
		return new String(c);
	}

	/**
	 * 判断是否为中文
	 * 
	 * @param c
	 * @return
	 */
	final private static boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}

	/**
	 * 判断是否是手机号码
	 * 
	 * @param text
	 * @return
	 */
	final public static boolean isMobileNO(String mobiles) {
//		String regExp = "^[1]([3][0-9]{1}|59|58|88|89)[0-9]{8}$";
		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	/**
	 * bytes[]转换成Hex字符�?可用于URL转换，IP地址转换.
	 * */
	final public static String bytesToHexString(byte[] bytes) {
		// http://stackoverflow.com/questions/332079
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(0xFF & bytes[i]);
			if (hex.length() == 1) {
				sb.append('0');
			}
			sb.append(hex);
		}
		return sb.toString();
	}

	final public static String stringToStringSHA_1(String str) {
		String cacheKey = str;
		MessageDigest mDigest;
		try {
			mDigest = MessageDigest.getInstance("SHA-1");
			mDigest.update(str.getBytes());
			cacheKey = StringHelper.bytesToHexString(mDigest.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return cacheKey;
	}

	final public static String prettyBytes(long value) {

		String args[] = { "B", "KB", "MB", "GB", "TB" };
		StringBuilder sb = new StringBuilder();
		int i;
		if (value < 1024L) {
			sb.append(String.valueOf(value));
			i = 0;
		} else if (value < 1048576L) {
			sb.append(String.format("%.1f", value / 1024.0));
			i = 1;
		} else if (value < 1073741824L) {
			sb.append(String.format("%.2f", value / 1048576.0));
			i = 2;
		} else if (value < 1099511627776L) {
			sb.append(String.format("%.3f", value / 1073741824.0));
			i = 3;
		} else {
			sb.append(String.format("%.4f", value / 1099511627776.0));
			i = 4;
		}
		sb.append(' ');
		sb.append(args[i]);
		return sb.toString();
	}

	/**
	 * 将Excepiton信息转换成String字符�?
	 * */
	final public static String exceptionToString(Throwable t) {
		if (t == null)
			return null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			t.printStackTrace(new PrintStream(baos));
		} finally {
			try {
				baos.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return baos.toString();
	}

	final public static String getPriceSpread(String price1, String price2) {

		try {
			Float saveMoney = Float.valueOf(price1) - Float.valueOf(price2);
			saveMoney = Math.abs(saveMoney);
			return new DecimalFormat("###0.00").format(saveMoney);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return "0.00";
		}
	}

	final public static String formatDouble(double d) {
		return new DecimalFormat("###0.00").format(d);
	}

	final public static int string2Int(String string) {
		int result = 0;
		try {
			result = Integer.valueOf(string);
		} catch (NumberFormatException e) {
			result = -1;
			e.printStackTrace();
		}
		return result;
	}

	final public static String int2String(int value) {
		String result = null;
		try {
			result = String.valueOf(value);
		} catch (Exception e) {
			result = null;
			e.printStackTrace();
		}

		return result;
	}

	final public static String isCard(String str1) {
		String result = null;
		IdcardValidator idCard = new IdcardValidator();
		if (str1 == null || str1.equals("")) {
			result = "请输入身份证号码!";
		} else {
			int len = str1.length();
			if (len != 15 && len != 18) {
				result = "请填写15位或18位正确的身份证号码";
			} else {
				if (len == 18 && (!idCard.isValidate18Idcard((str1)))) {
					result = "请填写正确的18位身份证号码";
				} else if (len == 15 && (!idCard.isValidate15Idcard((str1)))) {
					result = "请填写正确的15位身份证号码";
				}
			}
		}
		return result;
	}

	final public static StringBuilder removeLastSeparator(StringBuilder source,
			String separator) {
		int pos = source.lastIndexOf(separator);
		if (pos != -1)
			return source.delete(pos, source.length());
		return source;
	}

	final public static String[] getCheckCode(CheckBox[] cbs, EditText[] ets) {
		StringBuilder ctStr = new StringBuilder();
		StringBuilder etStr = new StringBuilder();
		String[] results = new String[2];
		for (int i = 0; i < cbs.length; i++) {
			CheckBox cb = cbs[i];
			EditText et = ets[i];
			if (cb.isChecked()) {
				ctStr.append(cb.getTag()).append(STR_SEPARATOR);
				etStr.append(et.getText().toString()).append(STR_SEPARATOR);
			}
		}
		if (isText(ctStr.toString())) {
			ctStr = removeLastSeparator(ctStr, STR_SEPARATOR);
		}
		if (isText(etStr.toString())) {
			etStr = removeLastSeparator(etStr, STR_SEPARATOR);
		}
		results[0] = ctStr.toString();
		results[1] = etStr.toString();
		return results;

	}

	/** 按args匹配是不是32位数据库中的uuid值 */
	public static boolean isUUID(String args) {
		if (!isText(args)) {
			return false;
		}
		String reg = "[0-9a-z]{32}";
		boolean flag = args.matches(reg);
		return flag;
	}

	final public static int generateAge(String birthday) {
		if (!isText(birthday))
			return 0;
		Date birthdate;
		int age = 0;
		try {
			birthdate = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);
			Calendar currentDay = Calendar.getInstance();
			currentDay.setTime(birthdate);
			int year = currentDay.get(Calendar.YEAR);
			// 获取年龄
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
			String years = simpleDateFormat.format(new Date());
			age = Integer.parseInt(years) - year;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return age;
	}
}
